<?php
namespace App\GraphQL\Mutations\MarketingPolicy;

use App\Models\MarketingPolicy;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use App\Models\MarketingPolicyRule;

class Create
{

    /**
     * Return a value for the field.
     *
     * @param null $rootValue
     *            Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param mixed[] $args
     *            The arguments that were passed into the field.
     * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context
     *            Arbitrary data that is shared between all fields of a single query.
     * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo
     *            Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        $data = $args['input'];
        $authUser = auth()->user();
        $data['user_id']=$authUser->id;
        $this->validate($data);
        $policy = new MarketingPolicy($data);
        if ($policy->cate !=='FREE') {
            $rule = MarketingPolicyRule::find($data['policy_rule_id']);
            $policy->preference = $rule->preference;
        } else {
            $policy->preference = 0;
        }
        $policy->save();
        // 更新rules policy_id
        if(count($data['rules'])>0){
            MarketingPolicyRule::whereIn('id', $data['rules'])->update(['marketing_policy_id'=>$policy->id]);
        }
        // 更新份额
        return [
            'status' => '200',
            'message' => '创建成功'
        ];
    }

    public function validate($data)
    {
        $cates = [
            'DERATE',
            'ALLOWANCE',
            'FREE'
        ];
        $targets = [
            'MEMBER',
            'PARTNER'
        ];
        $rules = [
            'name' => [
                'required',
                'max:18'
            ],
            'cate' => [
                'required',
                Rule::in($cates)
            ],
            'target'=>[
                'required',
                Rule::in($targets)
            ],
        ];
        if ($data['cate'] !== 'FREE'){
            $rules['rules']=[
                'required',
                'array'
            ];
            $rules['policy_rule_id']=[
                'required',
                'numeric'
            ];
        }
        $messages = [
            'name.required' => '名称不能为空',
            'name.max' => '名称不能超过18个字',
            'target.required' => '目标用户不能为空',
            'target.in' => '目标用户不能超出限制',
            'cate.required' => '类型不能为空',
            'cate.in' => '类型不能超出限制',
            'rules.required' => '规则不能为空',
            'rules.array' => '规则为数组',
            "policy_rule_id.required"=>"优惠幅度不能为空",
            "policy_rule_id.numeric"=>"优惠幅度为数字"
        ];
        $validate = Validator::make($data, $rules, $messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
        if ($data['cate'] !== 'FREE'){
            if (MarketingPolicyRule::whereIn('id',$data['rules'])->count() != count($data['rules'])){
                throw new \Exception('规则数量不匹配!');
            }
            $rule = MarketingPolicyRule::find($data['policy_rule_id']);
            if (!$rule){
                throw new \Exception('规则不存在!');
            }
            if ($rule->cate !== $data['cate']){
                throw new \Exception('规则与类型不匹配!');
            }
        }

        return true;
    }
}
